import hashlib
import base64
import os
import zipfile
import yaml
import ruamel.yaml


def md5(s):
    # 生成md5对象
    _md5 = hashlib.md5()
    # 转码
    password_str = str(s).encode(encoding='utf-8')
    # 加密操作
    _md5.update(password_str)
    return _md5.hexdigest()


def img_to_base64(img):
    with open(img, 'rb') as f:
        image_data = f.read()
        base64_data = base64.b64encode(image_data).decode('utf-8')
        prefix = 'data:image/png;base64,'
        # print("当前工作目录:", os.getcwd())
        # print("尝试打开:", os.path.abspath(img))
        return prefix + base64_data


def load_yaml(file):
    with open(file, encoding='utf-8') as f:
        return yaml.safe_load(f)


def load_ids(file):
    datas = load_yaml(file)
    for data in datas:
        yield data.get("id")


def load_yaml_ids(file):
    return {"argvalues": load_yaml(file),
            "ids": load_ids(file)}


def translate(text):
    return text.replace('":', '=').replace('="', '=')


def zip_dir(startdir, zip_file):
    # 压缩文件夹
    _zip_file = os.path.join(startdir, zip_file)
    if os.path.exists(_zip_file):
        # 先删除
        os.remove(_zip_file)
    z = zipfile.ZipFile(_zip_file, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(startdir):
        fpath = dir_path.replace(startdir, '')  # 不replace，就从根目录开始复制
        fpath = fpath and fpath + os.sep or ''
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), fpath + filename)
    z.close()



# def read_and_replace_yaml(file_path, replacements):
#     """
#     读取YAML文件并替换其中的变量，支持多层级嵌套，并保持字典顺序。
#     :param file_path: str, YAML文件路径
#     :param replacements: dict, 替换的键值对
#     :return: dict, 更新后的YAML数据
#     """
#
#     def recursive_replace(data, replacements):
#         """
#         递归地遍历字典或列表，并进行替换。
#         :param data: dict 或 list, 需要替换的YAML数据
#         :param replacements: dict, 替换的键值对
#         :return: dict 或 list, 替换后的数据
#         """
#         if isinstance(data, dict):
#             for key, value in data.items():
#                 # 如果找到匹配的键则替换值
#                 if key in replacements:
#                     data[key] = replacements[key]
#                 # 递归调用以替换嵌套数据
#                 elif isinstance(value, (dict, list)):
#                     data[key] = recursive_replace(value, replacements)
#         elif isinstance(data, list):
#             for index, item in enumerate(data):
#                 if isinstance(item, (dict, list)):
#                     data[index] = recursive_replace(item, replacements)
#         return data
#
#     # 使用新的方式来加载YAML文件
#     yaml = ruamel.yaml.YAML(typ='safe', pure=True)
#
#     # 设置缩进选项，确保字典顺序不变，并确保字典项不压缩为一行
#     yaml.indent(offset=4, mapping=4, sequence=6)
#
#     # 设置default_flow_style=False，确保字典不会显示为单行
#     yaml.default_flow_style = False
#
#     with open(file_path, 'r', encoding='utf-8') as file:
#         data = yaml.load(file)
#
#     # 递归替换YAML数据中的变量
#     updated_data = recursive_replace(data, replacements)
#
#     # 将修改后的数据写回YAML文件，保持字典顺序，并格式化输出
#     with open(file_path, 'w', encoding='utf-8') as file:
#         yaml.dump(updated_data, file)
#
#     return updated_data


def read_and_replace_yaml(file_path, replacements):
    """
    读取YAML文件并替换其中的变量，支持多层级嵌套，并保持字典顺序。
    :param file_path: str, YAML文件路径
    :param replacements: dict, 替换的键值对
    :return: dict, 更新后的YAML数据
    """

    def recursive_replace(data, replacements):
        """
        递归地遍历字典或列表，并进行替换。
        :param data: dict 或 list, 需要替换的YAML数据
        :param replacements: dict, 替换的键值对
        :return: dict 或 list, 替换后的数据
        """
        if isinstance(data, dict):
            for key, value in data.items():
                # 如果找到匹配的键则替换值
                if key == 'id' and 'id' in replacements:
                    data[key] = replacements['id']
                # 递归调用以替换嵌套数据
                elif isinstance(value, (dict, list)):
                    data[key] = recursive_replace(value, replacements)
        elif isinstance(data, list):
            for index, item in enumerate(data):
                # 对于列表中的每个字典项，根据索引进行替换
                if isinstance(item, dict):
                    # 为不同的id设置不同的值
                    if index == 0:  # 对应test1
                        item['id'] = replacements.get('test1_id', item.get('id'))
                    elif index == 1:  # 对应test2
                        item['id'] = replacements.get('test2_id', item.get('id'))
                if isinstance(item, (dict, list)):
                    data[index] = recursive_replace(item, replacements)
        return data

    # 使用新的方式来加载YAML文件
    yaml = ruamel.yaml.YAML(typ='safe', pure=True)

    # 设置缩进选项，确保字典顺序不变，并确保字典项不压缩为一行
    yaml.indent(offset=4, mapping=4, sequence=6)
    yaml.default_flow_style = False

    with open(file_path, 'r', encoding='utf-8') as file:
        data = yaml.load(file)

    # 定义替换的变量，可以根据索引替换不同的值
    updated_data = recursive_replace(data, replacements)

    # 将修改后的数据写回YAML文件，保持字典顺序，并格式化输出
    with open(file_path, 'w', encoding='utf-8') as file:
        yaml.dump(updated_data, file)

    return updated_data


# s=img_to_base64(r"E:\pythonProject\PRAFramework68_pro\data\avatar.png")
# print(s)







